﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.DataConvertLib;

namespace SerialPortDemo_07
{
    public partial class MarinForm : Form
    {
        private MySerialPort _serialPort = new MySerialPort();
        private Action<byte[]> Received;

        public MarinForm()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (!_serialPort.open)
                {
                    _serialPort.OpenBy(comboxPortName.Text, int.Parse(comboBoxBaudRate.Text));

                    buttonOpen.Text = "关闭串口";
                }
                else
                {
                    _serialPort.Close();

                    buttonOpen.Text = "打开串口";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MarinForm_Load(object sender, EventArgs e)
        {
            _serialPort.InitBy(comboxPortName, comboBoxBaudRate);

            _serialPort.Handler = new ModbusRtuDataHandler(); // 使用modbus rtu协议
            _serialPort.ShowLogEvent += (message) => Invoke(new Action(() => textBoxLog.AppendText(message + "\r\n")));
            _serialPort.ReceivedEvent += ReceivedHandel;
        }

        private void ReceivedHandel(byte[] bytes)
        {
            Received?.Invoke(bytes);
        }

        private void buttonRead_Click(object sender, EventArgs e)
        {
            try
            { 
                ByteBuffer byteBuffer = new ByteBuffer(new byte[] { 0x01, 0x03, 0x00, 0x00, 0x00, 0x64 ,0x44, 0x21 });

                _serialPort.Write(byteBuffer.toByteArray());

                Received = ReadResponse;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ReadResponse(byte[] bytes)
        {
            Invoke(new Action(() => MessageBox.Show("串口有数据传来")));

        }

        private void buttonRead1_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] request = CRC.crc16(new byte[] { 0x01, 0x03, 0x00, 0x01, 0x00, 0x03 });;

                _serialPort.Write(request);

                Received = Read1Response;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Read1Response(byte[] buffer)
        {
            Invoke(new Action(() =>
            {
                ByteBuffer byteBuffer = new ByteBuffer(buffer);

                // 响应的数据
                // 01 03 06 00 00 00 02 00 00 80 B5
                // 0x01 -- 从机地址；  0x03 -- 功能码； 0x06 -- 数据长度
                // 0x00 0x00 -- 第一个寄存器的值
                // 0x00 0x02 -- 第二个寄存器的值
                // 0x00 0x00 -- 第三个寄存器的值
                // 0x80 0xB5 -- 校验位

                byteBuffer.popByte(); // 0x01 -- 从机地址；
                byteBuffer.popByte(); // 0x03 -- 功能码；
                byteBuffer.popByte(); // 0x06 -- 数据长度

                textBoxAddress1.Text = byteBuffer.popShort().ToString(); // 0x00 0x00 -- 第一个寄存器的值
                textBoxAddress2.Text = byteBuffer.popShort().ToString(); // 0x00 0x02 -- 第二个寄存器的值
                textBoxAddress3.Text = byteBuffer.popShort().ToString(); // 0x00 0x00 -- 第三个寄存器的值

                MessageBox.Show("解析完成");
            }));

        }

        private void buttonWrite_Click(object sender, EventArgs e)
        {
            try
            {
                ByteBuffer requestBuffer = new ByteBuffer();
                //byte[] request = new byte[] { 0x01, 0x10, 0x00, 0x01, 0x00, 0x03, 0x06 };
                // 响应的数据
                // 0x01, 0x10, 0x00, 0x01, 0x00, 0x03, 0x06
                // 0x01 -- 从机地址；  0x10 -- 功能码；
                // 0x00 0x01 -- 起始地址
                // 0x00 0x03 -- 寄存器个数
                // 0x06 -- 字节计数
                requestBuffer.pushByteArray(new byte[] { 0x01, 0x10, 0x00, 0x01, 0x00, 0x03, 0x06 });
                requestBuffer.pushShort(short.Parse(textBoxAddressWrite1.Text));
                requestBuffer.pushShort(short.Parse(textBoxAddressWrite2.Text));
                requestBuffer.pushShort(short.Parse(textBoxAddressWrite3.Text));

                _serialPort.Write(CRC.crc16(requestBuffer.toByteArray()));

                Received = WriteRespnose;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void WriteRespnose(byte[] buffer)
        {
            MessageBox.Show("写入成功");
        }
    }
}
